package org.example.ims.Service.Base.Impl;

import org.example.ims.Entity.Base.Category;
import org.example.ims.Repository.Base.CategoryRepository;
import org.example.ims.Service.Base.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import java.util.Optional;

@Service("categoryService")
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryRepository categoryRepository;

    @Override
    /*这里插入没有逻辑判断，简单形式，而且没有ID才成功，对于异常没有处理*/
    public Category addCategory(Category category) {
        return categoryRepository.save(category);
    }


    /*示例但是不能用*/
    @Override
    public Category addCategory2(Category category) {
        if (!categoryRepository.existsById(999)) {
            Category temp = new Category();
            temp.setCategoryId(999); // 设置 ID，但下面会清除
            temp.setCategoryName("Manual Insert");

            // 强制清空 ID，让 JPA 认为是新实体
            temp.setCategoryId(null);

            categoryRepository.save(temp); // 会执行 INSERT
        }
        else {
            throw new RuntimeException("ID already exists");
        }
        return null;
    }

    @Override
    public Optional<Category> findCategoryById(Integer categoryId) {
        return categoryRepository.findById(categoryId);
    }

    @Override
    public Page<Category> findAllCategories(Integer page, Integer size) {

        return categoryRepository.findAll(PageRequest.of(page, size));
    }

    @Override
    public Page<Category> searchCategories(String name, Integer page, Integer size) {
        return categoryRepository.searchCategories(
                name, PageRequest.of(page, size)
        );
    }


    @Override
    public Category updateCategory(Integer categoryId, Category categoryDetails) {
        return categoryRepository.findById(categoryId)
                .map(category -> {
                    category.setCategoryName(categoryDetails.getCategoryName());
                    return categoryRepository.save(category);
                })
                .orElseThrow(() -> new RuntimeException("Category not found"));
    }

    @Override
    public void deleteCategoryById(Integer categoryId) {
        if (!categoryRepository.existsById(categoryId)) {
            throw new RuntimeException("Category does not exist");
        }
        categoryRepository.deleteById(categoryId);
    }
}
